package com.lingx.web.core.urihanlder;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.lingx.utils.Utils;
import com.lingx.web.api.ApiService;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
@Component
public class ApiHandler implements IUriHandler {

	@Override
	public String getUri() {
		return "/api";
	}
	@Resource
	private ApiService apiService;
	@Override
	public void handler(ChannelHandlerContext ctx, FullHttpRequest request) {
		String reqJsonStr=null;
		try {
			byte bytes[] = new byte[request.content().readableBytes()];
			request.content().readBytes(bytes);
			 reqJsonStr = new String(bytes,Charset.forName("UTF-8"));
			//ApiService apiService = RestApp.SPRINGCONTEXT.getBean(ApiService.class);
			Map<String, Object> params =(Map<String, Object>) JSON.parse(reqJsonStr);
			String ip=request.headers().get("X-Real-IP");//!=null?request.headers().get("X-Real-IP"):((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress()
			if(ip==null) {
				ip = request.headers().get("X-Forwarded-For");
				if(Utils.isNotNull(ip)){
				   ip = ip.split(",")[0];
				}
			}
			if(ip==null) {
				try {
					ip=((InetSocketAddress)ctx.channel().remoteAddress()).getAddress().getHostAddress();
				} catch (Exception e) {
					//e.printStackTrace();
					//channel已断开，不需要处理了
					return;
				}
			}
			if(ip==null)ip="none";
			params.put("X-Real-IP", ip);
			
			
			Map<String, Object> ret = apiService.callApi(params);
			//System.out.println(JSON.toJSONString(ret));
			FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
					Unpooled.wrappedBuffer(JSON.toJSONString(ret).getBytes("UTF-8")));
			
			// Thread.currentThread().sleep(1000);
			response.headers().set("Access-Control-Allow-Origin", "*");
			response.headers().add("Access-Control-Allow-Methods", "GET,POST");
			response.headers().set("Content-Type", "application/json; charset=UTF-8");
			response.headers().setInt("Content-Length", response.content().readableBytes());
			//System.out.println("准备回复数据，长度:"+response.content().readableBytes());
			//Thread.currentThread().sleep(5000);
			ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
			//ctx.close();
			params.clear();
			params=null;
			ret.clear();
			ret=null;
			reqJsonStr=null;
			bytes=null;
			ip=null;
			request=null;
			response=null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("REQ:"+reqJsonStr);
			e.printStackTrace();
		}
	}

}
